import axios from "axios";
import {getGenCTicket ,wxSilentLogin} from "@/utils/api.js";

const platform = import.meta.env.VITE_PLATFORM_IP
const  init = async () =>{
    const appid = 'wx1a6f7877ecdd68a8'
    const url = encodeURIComponent(location.origin) ;
    const access_url  = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}/home&response_type=code&scope=snsapi_base#wechat_redirect`;
    const params = new URLSearchParams(location.search)
    if(!params.get('code')){
        const v = await wxSilentLogin({csProjectAppid: 'dhlj_wxgzh', code: params.get('code')})
        if(v?.c === '100'){
            window.localStorage.setItem('CTK_token',v?.d)
        }
    }
}

const server= axios.create({
    // baseURL: import.meta.env.VITE_BASE_URL,
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 1000 * 5,
    headers:{
        "Cache-Control":"no-cache"
    }
});
server.interceptors.request.use(config => {
   const ctk = window.localStorage.getItem('CTK') || null
   if(ctk){
       config.headers.CTK = ctk
   }
    return config;
}, error => {
    return Promise.reject(error);
});

server.interceptors.response.use(async  response => {
    if(response.data.c === '400'){
        getGenCTicket({platform}).then(v =>{
            if(v?.c === "100"){
                window.localStorage.setItem('CTK',v?.d)
            }
        })
    }
    // if(response.data.c === '400'){
    //     await init()
    // }
    return response.data;
}, error => {
    return Promise.reject(error);
});


function request(url, method, parameter) {
    return server({
        url,
        method,
        data: method === "post" ? parameter: '',
        params: method === "get" ? parameter : ''
    })
}

export function apiGet(url, parameter) {
    return request(url, "get", parameter)
}


export function apiPost(url, parameter) {
    return request(url, "post", parameter)
}
export default server